package cn.sportvip.service.user;

import java.net.URLEncoder;
import java.util.UUID;

import javax.mail.internet.MimeMessage;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.sportvip.dto.user.UserInfoDto;
import cn.sportvip.entity.user.Credential;
import cn.sportvip.entity.user.Feedback;
import cn.sportvip.entity.user.FindPassword;
import cn.sportvip.entity.user.UserInfo;
import cn.sportvip.exception.GeneralException;
import cn.sportvip.repository.jpa.user.CredentialRepository;
import cn.sportvip.repository.jpa.user.FeedbackRepository;
import cn.sportvip.repository.jpa.user.FindPasswordRepository;
import cn.sportvip.repository.jpa.user.UserInfoRepository;

import com.alibaba.fastjson.JSONObject;

@Service
public class UserService {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

	@Autowired
	private CredentialRepository credentialRepository;
	
	@Autowired
	private UserInfoRepository userInfoRepository;
	
	@Autowired
	private FindPasswordRepository findPasswordRepository;
	
	@Autowired
	private FeedbackRepository feedbackRepository;
	
	@Autowired
	private JavaMailSender javaMailSender;
	/**注册*/
	@Transactional
	public UserInfo register(Credential credential, UserInfo userInfo) {
		if(credentialRepository.findByEmail(credential.getEmail()) != null){
			throw new GeneralException("该邮箱已经注册！");
		}
		if(credentialRepository.findByPhone(credential.getPhone()) != null){
			throw new GeneralException("该手机号码已经注册！");
		}
		credential.setUserInfo(userInfo);
		credentialRepository.save(credential);
		return userInfo;
	}
	/**登陆*/
	@Transactional(readOnly = true)
	public UserInfoDto login(String identifier, String password) {
		Credential credential = null;
		if(identifier.indexOf('@') > -1) {// email
			credential = credentialRepository.findByEmail(identifier);
		} else {// phone
			credential = credentialRepository.findByPhone(identifier);
		}
		if(credential == null) {
			throw new GeneralException("该用户尚未注册！");
		}
		if(!credential.getPassword().equals(password)) {
			throw new GeneralException("用户名或密码错误！");
		}
		return new UserInfoDto(credential.getUserInfo(), credential);
	}
	/**更新用户资料*/
	@Transactional
	public UserInfo updateUserInfo(UserInfo userInfo) {
		UserInfo oldInfo = userInfoRepository.findOne(userInfo.getId());
		try {
			BeanUtils.copyProperties(oldInfo, userInfo);
		} catch (Exception e) {
			LOGGER.warn("更新用户信息错误!", e);
			throw new GeneralException("用户信息更新失败，请重新输入!");
		}
		userInfoRepository.save(oldInfo);
		return oldInfo;
	}
	/**更新用户登陆信息*/
	@Transactional
	public Credential updateCredentail(Credential newCredential, String emailOrPhone, String password) {	
		UserInfoDto old = login(emailOrPhone, password);
		Credential credential = credentialRepository.findOne(old.id);
		credential.setPassword(newCredential.getPassword());
		return credential;
	}
	/**忘记密码*/
	@Transactional
	public JSONObject forgotPassword(String email) {
		FindPassword findPassword = findPasswordRepository.findOne(email);
		if(findPassword == null){
			findPassword = new FindPassword();
			findPassword.setEmail(email);
		}
		findPassword.setKey(UUID.randomUUID().toString());
		findPasswordRepository.save(findPassword);
		// 发邮件
		MimeMessage message = javaMailSender.createMimeMessage();
		MimeMessageHelper helper = null;
		try {
			String url = String.format("http://yundongvip.cn/api/user/gotoResetPassword/%s/%s", URLEncoder.encode(email,"utf8"), findPassword.getKey());
			helper = new MimeMessageHelper(message, true);
			helper.setTo(email);
			helper.setText("<html><body><a src='"+url+"'>点击此处重置您的密码</a><br>若无法打开请复制链	到您的浏览器地址栏访问<br>"+url+"</body></html>", true);
			helper.setSubject("重置密码服务");
			helper.setFrom("sport2015@sina.com");
			javaMailSender.send(message);
		} catch (Exception e) {
			throw new GeneralException("发送重置密码邮件失败，请重试！");
		}
		
		JSONObject msg = new JSONObject();
		msg.put("msg", "一封修改密码邮件已经发送到您的注册邮箱，请注意查收！");
		return msg;
	}
	
	@Transactional(readOnly = true)
	public boolean validateResetPasswordRequest(String email, String uuid) {
		FindPassword find =  findPasswordRepository.findOne(email);
		if(find !=null && find.getKey().equals(uuid)) {
			return true;
		}
		return false;
	}
	
	@Transactional
	public boolean emailResetPassword(String email, String uuid,
			String newPassword) {
		if(!validateResetPasswordRequest(email, uuid)){
			return false;
		}
		findPasswordRepository.delete(email);
		Credential credential = credentialRepository.findByEmail(email);
		credential.setPassword(newPassword);
		return true;
	}
	
	@Transactional
	public Feedback addFeedback(Feedback feedback) {
		return feedbackRepository.save(feedback);
	}
}
